package com.uduemc.biso.node.module.common.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.uduemc.biso.core.extities.center.SysComponentType;
import com.uduemc.biso.node.core.common.entities.FormComponent;
import com.uduemc.biso.node.core.common.entities.SiteComponent;
import com.uduemc.biso.node.core.common.entities.SiteComponentSimple;
import com.uduemc.biso.node.core.common.entities.publishdata.databody.ComponentData;
import com.uduemc.biso.node.core.common.entities.publishdata.databody.ComponentSimpleData;
import com.uduemc.biso.node.core.common.entities.publishdata.databody.componentdata.*;
import com.uduemc.biso.node.core.common.entities.sitecomponent.RepertoryData;
import com.uduemc.biso.node.core.dto.FeignFindInfosBySystemIdAndIds;
import com.uduemc.biso.node.core.entities.*;
import com.uduemc.biso.node.core.entities.custom.Article;
import com.uduemc.biso.node.core.entities.custom.CategoryQuote;
import com.uduemc.biso.node.core.entities.custom.ProductDataTableForList;
import com.uduemc.biso.node.core.entities.custom.RepertoryQuote;
import com.uduemc.biso.node.core.utils.SiteUrlUtil;
import com.uduemc.biso.node.module.common.mapper.CRepertoryMapper;
import com.uduemc.biso.node.module.common.service.CArticleService;
import com.uduemc.biso.node.module.common.service.CComponentService;
import com.uduemc.biso.node.module.common.service.CProductService;
import com.uduemc.biso.node.module.common.service.CPublishService;
import com.uduemc.biso.node.module.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class CComponentServiceImpl implements CComponentService {

	@Autowired
	public CPublishService cPublishServiceImpl;

	@Autowired
	public SComponentService sComponentServiceImpl;

	@Autowired
	public SComponentFormService sComponentFormServiceImpl;

	@Autowired
	private SComponentSimpleService sComponentSimpleServiceImpl;

	@Autowired
	private SComponentQuoteSystemService sComponentQuoteSystemServiceImpl;

	@Autowired
	private SysComponentTypeService sysComponentTypeServiceImpl;

	@Autowired
	private SContainerService sContainerServiceImpl;

	@Autowired
	private SRepertoryQuoteService sRepertoryQuoteServiceImpl;

	@Autowired
	private CRepertoryMapper cRepertoryMapper;

	@Autowired
	private SPageService sPageServiceImpl;

	@Autowired
	private SSystemService sSystemServiceImpl;

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private CArticleService cArticleServiceImpl;

	@Autowired
	private CProductService cProductServiceImpl;

	@Autowired
	private SSystemItemCustomLinkService sSystemItemCustomLinkServiceImpl;

	@Transactional
	@Override
	public void publish(long hostId, long siteId, long pageId, ComponentData componentData, ThreadLocal<Map<String, Long>> containerTmpIdHolder,
			ThreadLocal<Map<String, Long>> componentTmpIdHolder) {

		Map<String, Long> containerTmpId = containerTmpIdHolder.get();
		Map<String, Long> componentTmpId = componentTmpIdHolder.get();

		// 插入数据
		List<ComponentDataItemInsert> insertList = componentData.getInsert();
		insertList(hostId, siteId, insertList, containerTmpId, componentTmpId);

		// 更新数据
		List<ComponentDataItemUpdate> updateList = componentData.getUpdate();
		updateList(hostId, siteId, updateList, containerTmpId, componentTmpId);

		// 删除数据
		List<ComponentDataItemDelete> deleteList = componentData.getDelete();
		deleteList(hostId, siteId, deleteList);

	}

	@Transactional
	@Override
	public void publish(long hostId, long siteId, List<ComponentSimpleData> sComponentSimple) {
		if (CollectionUtils.isEmpty(sComponentSimple)) {
			return;
		}
		for (ComponentSimpleData componentSimpleData : sComponentSimple) {
			SComponentSimple sCompSimple = sComponentSimpleServiceImpl.findByHostSiteTypeIdNotAndCreate(hostId, componentSimpleData.getSiteId(),
					componentSimpleData.getTypeId());

			sCompSimple.setStatus(componentSimpleData.getStatus()).setName(componentSimpleData.getName()).setContent(componentSimpleData.getContent())
					.setConfig(componentSimpleData.getConfig());

			sComponentSimpleServiceImpl.updateByIdSelective(sCompSimple);

			List<RepertoryQuote> listRepertoryQuote = sRepertoryQuoteServiceImpl.findRepertoryQuoteByHostSiteTypeAimId(hostId, siteId, (short) 12,
					sCompSimple.getId(), "`s_repertory_quote`.`order_num` ASC");

			List<Long> ids = new ArrayList<>();
			if (CollectionUtils.isEmpty(listRepertoryQuote)) {
				listRepertoryQuote.forEach(item -> {
					ids.add(item.getSRepertoryQuote().getRepertoryId());
				});
			}

			if (CollectionUtils.isEmpty(componentSimpleData.getRepertoryIds())) {
				// 删除所有现有的
				sRepertoryQuoteServiceImpl.deleteByHostSiteAimIdAndType(hostId, siteId, (short) 12, sCompSimple.getId());
			} else {
				SRepertoryQuote sRepertoryQuote = null;
				for (int i = 0; i < componentSimpleData.getRepertoryIds().size(); i++) {
					Long repertoryId = componentSimpleData.getRepertoryIds().get(i);

					if (CollectionUtils.isEmpty(listRepertoryQuote)) {
						// 增加
						sRepertoryQuote = new SRepertoryQuote();
						sRepertoryQuote.setAimId(sCompSimple.getId()).setConfig("").setHostId(hostId).setOrderNum(i + 1).setParentId(0L)
								.setRepertoryId(repertoryId).setSiteId(siteId).setType((short) 12);
						sRepertoryQuoteServiceImpl.insert(sRepertoryQuote);
					} else {
						if (i <= listRepertoryQuote.size() - 1) {
							sRepertoryQuote = listRepertoryQuote.get(i).getSRepertoryQuote();
							if (sRepertoryQuote.getRepertoryId().longValue() != repertoryId.longValue()) {
								sRepertoryQuote.setRepertoryId(repertoryId);
								sRepertoryQuoteServiceImpl.updateByIdSelective(sRepertoryQuote);
							}
						} else {
							// 增加
							sRepertoryQuote = new SRepertoryQuote();
							sRepertoryQuote.setAimId(sCompSimple.getId()).setConfig("").setHostId(hostId).setOrderNum(i + 1).setParentId(0L)
									.setRepertoryId(repertoryId).setSiteId(siteId).setType((short) 12);
							sRepertoryQuoteServiceImpl.insert(sRepertoryQuote);
						}
					}
				}

				if (listRepertoryQuote.size() > componentSimpleData.getRepertoryIds().size()) {
					for (int i = componentSimpleData.getRepertoryIds().size(); i < listRepertoryQuote.size(); i++) {
						sRepertoryQuoteServiceImpl.deleteById(listRepertoryQuote.get(i).getSRepertoryQuote().getId());
					}
				}
			}

		}
	}

	@Transactional
	@Override
	public void insertList(long hostId, long siteId, List<ComponentDataItemInsert> componentDataItemInsertList, Map<String, Long> containerTmpId,
			Map<String, Long> componentTmpId) {
		if (CollectionUtils.isEmpty(componentDataItemInsertList)) {
			return;
		}
		Iterator<ComponentDataItemInsert> iterator = componentDataItemInsertList.iterator();
		while (iterator.hasNext()) {
			ComponentDataItemInsert componentDataItemInsert = iterator.next();
			SComponent sComponent = componentDataItemInsert.makeSComponent(hostId, siteId, containerTmpId);
			if (sComponent == null) {
				throw new RuntimeException("通过 componentDataItemInsert 获取 sComponent 数据失败 componentDataItemInsert： " + componentDataItemInsert.toString());
			}

			SComponent insert = sComponentServiceImpl.insert(sComponent);
			if (insert == null || insert.getId() == null || insert.getId().longValue() < 1) {
				throw new RuntimeException("写入 sComponent  数据失败 sComponent： " + sComponent.toString());
			}

			componentTmpId.put(componentDataItemInsert.getTmpId(), insert.getId());

			// 对引用系统部分的配置进行更新
			updateQuoteSystem(insert, componentDataItemInsert.getQuoteSystem());

			List<ComponentRepertoryData> componentRepertoryDataList = componentDataItemInsert.getRepertoryData();
			if (!CollectionUtils.isEmpty(componentRepertoryDataList)) {
				insertRepertoryQuote(componentRepertoryDataList, hostId, siteId, 0L, insert.getId());
			}
		}
	}

	protected void insertRepertoryQuote(List<ComponentRepertoryData> componentRepertoryDataList, long hostId, long siteId, long parentId, long aimId) {
		Iterator<ComponentRepertoryData> iteratorRepertoryData = componentRepertoryDataList.iterator();
		int orderNum = 1;
		while (iteratorRepertoryData.hasNext()) {
			ComponentRepertoryData repertoryData = iteratorRepertoryData.next();

			SRepertoryQuote sRepertoryQuote = new SRepertoryQuote();
			// 肯定是新增数据
			sRepertoryQuote.setId(null);
			sRepertoryQuote.setHostId(hostId);
			sRepertoryQuote.setSiteId(siteId);
			sRepertoryQuote.setParentId(parentId).setRepertoryId(repertoryData.getRepertoryId()).setType((short) 11);
			sRepertoryQuote.setAimId(aimId);
			sRepertoryQuote.setOrderNum(
					repertoryData.getOrderNum() == null || repertoryData.getOrderNum().intValue() < 1 ? orderNum : repertoryData.getOrderNum().intValue())
					.setConfig(repertoryData.getConfig());
			SRepertoryQuote insertSRepertoryQuote = sRepertoryQuoteServiceImpl.insert(sRepertoryQuote);
			if (insertSRepertoryQuote == null || insertSRepertoryQuote.getId() == null || insertSRepertoryQuote.getId().longValue() < 1) {
				throw new RuntimeException("写入数据失败，insertSRepertoryQuote ： " + insertSRepertoryQuote.toString());
			}
			orderNum++;

			List<ComponentRepertoryData> child = repertoryData.getChildren();
			if (!CollectionUtils.isEmpty(child)) {
				insertRepertoryQuote(child, hostId, siteId, insertSRepertoryQuote.getId(), aimId);
			}
		}
	}

	@Override
	public List<SiteComponent> findByHostSitePageId(long hostId, long siteId, long pageId) throws JsonParseException, JsonMappingException, IOException {
		List<SComponent> listSComponent = sComponentServiceImpl.findByHostSitePageId(hostId, siteId, pageId, (short) 0);
		List<SiteComponent> listSiteComponent = new ArrayList<SiteComponent>();

		// 需要一次性查询资源数据库的ids
		List<Long> aimIds = new ArrayList<>();
		// 需要一次性查询引用系统数据的ids
		List<Long> qsIds = new ArrayList<>();
		Iterator<SComponent> iterator = listSComponent.iterator();
		while (iterator.hasNext()) {
			SComponent sComponent = iterator.next();

			// 是否需要查询资源库
			if (mustSelectRepertoryTypeId(sComponent.getTypeId())) {
				aimIds.add(sComponent.getId());
			}

			if (mustSelectQuoteSystemConfig(sComponent.getTypeId())) {
				qsIds.add(sComponent.getId());
			}

			SiteComponent siteComponent = new SiteComponent();
			siteComponent.setComponent(sComponent);
			listSiteComponent.add(siteComponent);
		}

		// 给组件数据补充资源库数据引用部分
		dataBindRepertoryQuote(listSiteComponent, aimIds, hostId, siteId);

		// 给组件数据补充系统资源引用部分数据
		dataBindComponentQuote(listSiteComponent, qsIds, hostId, siteId);

		return listSiteComponent;
	}

	@Override
	public SiteComponent findByHostSiteIdAndId(long hostId, long siteId, long id) {
		return null;
	}

	@Transactional
	@Override
	public void updateList(long hostId, long siteId, List<ComponentDataItemUpdate> componentDataItemUpdateList, Map<String, Long> containerTmpId,
			Map<String, Long> componentTmpId) {
		if (CollectionUtils.isEmpty(componentDataItemUpdateList)) {
			return;
		}
		Iterator<ComponentDataItemUpdate> iterator = componentDataItemUpdateList.iterator();
		while (iterator.hasNext()) {
			ComponentDataItemUpdate componentDataItemUpdate = iterator.next();
			SComponent sComponent = componentDataItemUpdate.makeSComponent(hostId, siteId, containerTmpId, componentTmpId);
			if (sComponent == null) {
				throw new RuntimeException("通过 componentDataItemUpdate 获取 sComponent 数据失败 componentDataItemUpdate： " + componentDataItemUpdate.toString());
			}

			// 数据库查询该条数据是否存在
			boolean exist = sComponentServiceImpl.isExist(sComponent.getId(), sComponent.getHostId(), sComponent.getSiteId());
			if (!exist) {
				throw new RuntimeException("对 sComponent 数据进行更新失败，不存在id, 该条数据 sComponent： " + sComponent.toString());
			}

			Long containerId = sComponent.getContainerId();
			Long containerBoxId = sComponent.getContainerBoxId();
			if (containerId == null || containerId.longValue() < 1 || containerBoxId == null || containerBoxId.longValue() < 1) {
				throw new RuntimeException("对 sComponent 数据进行更新失败，不存在containerId,containerBoxId异常, 该条数据 sComponent： " + sComponent.toString());
			}

			SContainer containerBox = sContainerServiceImpl.findOne(containerId);
			if (containerBox == null || containerBox.getId() == null || containerBox.getId().longValue() < 1 || containerBox.getBoxId() == null
					|| containerBox.getBoxId().longValue() < 1) {
				throw new RuntimeException("通过查询数据库 containerId 不存在, sComponent： " + sComponent.toString());
			}

			// containerBox 的 boxId 与 containerBoxId也要相互对应一致才行
			if (containerBox.getBoxId().longValue() != containerBoxId.longValue()
					|| !sContainerServiceImpl.isExist(containerBoxId, sComponent.getHostId(), sComponent.getSiteId(), sComponent.getPageId())) {
				throw new RuntimeException("通过查询数据库 containerBoxId 不存在或者 boxId 无法对应, sComponent： " + sComponent.toString());
			}

			// 更新
			SComponent update = sComponentServiceImpl.updateById(sComponent);
			if (update == null || update.getId() == null || update.getId() < 1) {
				throw new RuntimeException("对 sComponent 数据进行更新失败： " + sComponent.toString());
			}

			// 对引用系统部分的配置进行更新
			updateQuoteSystem(sComponent, componentDataItemUpdate.getQuoteSystem());

			List<ComponentRepertoryData> componentRepertoryDataList = componentDataItemUpdate.getRepertoryData();
			sRepertoryQuoteServiceImpl.deleteByTypeAimId((short) 11, update.getId());
			insertRepertoryQuote(componentRepertoryDataList, hostId, siteId, 0L, update.getId());
		}
	}

	@Transactional
	@Override
	public void deleteList(long hostId, long siteId, List<ComponentDataItemDelete> componentDataItemDeleteList) {
		if (CollectionUtils.isEmpty(componentDataItemDeleteList)) {
			return;
		}
		Iterator<ComponentDataItemDelete> iterator = componentDataItemDeleteList.iterator();
		while (iterator.hasNext()) {
			ComponentDataItemDelete componentDataItemDelete = iterator.next();
			SComponent sComponent = sComponentServiceImpl.findByHostSiteIdAndId(componentDataItemDelete.getId(), hostId, siteId);
			if (sComponent == null) {
				throw new RuntimeException("通过 componentDataItemDelete的id 获取 sComponent 失败 componentDataItemDelete： " + componentDataItemDelete.toString());
			}

			// 修改状态为删除
			sComponent.setStatus((short) 4);
			SComponent updateAllById = sComponentServiceImpl.updateById(sComponent);
			if (updateAllById == null || updateAllById.getId() == null || updateAllById.getId().longValue() != sComponent.getId().longValue()) {
				throw new RuntimeException("更新 SComponent 状态为删除时失败, sComponent：" + sComponent.toString());
			}
		}
	}

	/**
	 * 必须要查询引用系统资源数据的判定
	 *
	 * @param typeId
	 * @return
	 */
	protected static boolean mustSelectQuoteSystemConfig(Long typeId) {
		if (typeId == null) {
			return false;
		}
		long[] inTypeId = new long[] { 13L, 14L, 15L };
		for (long id : inTypeId) {
			if (typeId.longValue() == id) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 必须要查询资源数据的组件类型判定
	 *
	 * @param typeId
	 * @return
	 */
	protected static boolean mustSelectRepertoryTypeId(Long typeId) {
		if (typeId == null) {
			return false;
		}
		long[] inTypeId = new long[] { 6L, 7L, 8L, 9L, 26L, 27L, 28L, 33L, 34L, 35L };
		for (long id : inTypeId) {
			if (typeId.longValue() == id) {
				return true;
			}
		}
		return false;
	}

	protected void updateQuoteSystem(SComponent sComponent, ComponentQuoteSystemConfig componentQuoteSystemConfig) {
		Long typeId = sComponent.getTypeId();
		if (typeId == null) {
			return;
		}
		boolean bool = mustSelectQuoteSystemConfig(typeId);
		if (!bool) {
			return;
		}
		SComponentQuoteSystem findByHostSiteComponentId = sComponentQuoteSystemServiceImpl.findByHostSiteComponentId(sComponent.getHostId(),
				sComponent.getSiteId(), sComponent.getId());
		if (findByHostSiteComponentId == null) {
			// 新增
			SComponentQuoteSystem sComponentQuoteSystem = componentQuoteSystemConfig.getSComponentQuoteSystem(sComponent.getHostId(), sComponent.getSiteId(),
					sComponent.getId());
			sComponentQuoteSystemServiceImpl.insert(sComponentQuoteSystem);
		} else {
			// 更新
			findByHostSiteComponentId.setType(componentQuoteSystemConfig.getType()).setQuotePageId(componentQuoteSystemConfig.getQuotePageId())
					.setQuoteSystemId(componentQuoteSystemConfig.getQuoteSystemId())
					.setQuoteSystemCategoryId(componentQuoteSystemConfig.getQuoteSystemCategoryId()).setTopCount(componentQuoteSystemConfig.getTopCount())
					.setQuoteSystemItemIds(componentQuoteSystemConfig.getQuoteSystemItemIds()).setRemark(componentQuoteSystemConfig.getRemark());
			sComponentQuoteSystemServiceImpl.updateById(findByHostSiteComponentId);
		}
	}

	/**
	 * 数据绑定，组件是否是否有需要引用资源的部分，如果有则进行数据绑定
	 */
	protected void dataBindRepertoryQuote(List<SiteComponent> listSiteComponent, List<Long> aimIds, long hostId, long siteId) {
		if (CollectionUtils.isEmpty(listSiteComponent)) {
			return;
		}

		if (!CollectionUtils.isEmpty(aimIds)) {
			List<RepertoryQuote> findRepertoryQuoteByHostSiteTypeInAimId = cRepertoryMapper.findRepertoryQuoteByHostSiteTypeInAimId(hostId, siteId, (short) 11,
					aimIds);
			if (!CollectionUtils.isEmpty(findRepertoryQuoteByHostSiteTypeInAimId)) {
				Iterator<SiteComponent> iteratorSiteComponent = listSiteComponent.iterator();
				while (iteratorSiteComponent.hasNext()) {
					SiteComponent nextSiteComponent = iteratorSiteComponent.next();
					if (nextSiteComponent.getComponent() != null && nextSiteComponent.getComponent().getId() != null
							&& nextSiteComponent.getComponent().getId().longValue() > 0) {
						List<RepertoryData> repertoryData = new ArrayList<>();
						Iterator<RepertoryQuote> iteratorRepertoryQuote = findRepertoryQuoteByHostSiteTypeInAimId.iterator();
						while (iteratorRepertoryQuote.hasNext()) {
							RepertoryQuote nextRepertoryQuote = iteratorRepertoryQuote.next();
							if (nextRepertoryQuote.getSRepertoryQuote() != null && nextRepertoryQuote.getSRepertoryQuote().getAimId() != null
									&& nextRepertoryQuote.getSRepertoryQuote().getAimId().longValue() == nextSiteComponent.getComponent().getId().longValue()) {
								repertoryData.add(RepertoryData.getRepertoryData(nextRepertoryQuote));
							}
						}

						// 针对此 repertoryData 重新整理成，通过 parent_id 有关系规则的数据
						List<RepertoryData> repertoryDataByParent = dataBindRepertoryQuoteByParentId(repertoryData);
						nextSiteComponent.setRepertoryData(repertoryDataByParent);
					}
				}
			}
		}
	}

	/**
	 * 数据库查询出来的 repertoryData 数据，通过 parentId 的关系罗列成为具有 child 关系的结构数据
	 *
	 * @param repertoryData
	 * @return
	 */
	protected List<RepertoryData> dataBindRepertoryQuoteByParentId(List<RepertoryData> repertoryData) {
		if (CollectionUtils.isEmpty(repertoryData)) {
			return new ArrayList<>();
		}
		List<RepertoryData> repertoryDataByParent = new ArrayList<>();
		for (RepertoryData item : repertoryData) {
			if (item.getParentId() != null && item.getParentId().longValue() == 0L) {
				dataBindRepertoryQuoteByParentId(item, repertoryData);
				repertoryDataByParent.add(item);
			}
		}

		return repertoryDataByParent;
	}

	/**
	 * 数据库查询出来的 repertoryData 数据，通过 parentId 的关系罗列成为具有 child 关系的结构数据
	 *
	 * @param repertoryDataByParent
	 * @param repertoryData
	 * @param parentId
	 */
	protected void dataBindRepertoryQuoteByParentId(RepertoryData repertoryDataByParent, List<RepertoryData> repertoryData) {
		if (CollectionUtils.isEmpty(repertoryData)) {
			return;
		}
		List<RepertoryData> child = new ArrayList<>();
		for (RepertoryData item : repertoryData) {
			if (item.getParentId() != null && item.getParentId().longValue() == repertoryDataByParent.getId()) {
				dataBindRepertoryQuoteByParentId(item, repertoryData);
				child.add(item);
				repertoryDataByParent.setChild(child);
			}
		}
	}

	/**
	 * 数据绑定，组件是否有需要绑定组件引用系统资源数据的部分，如果有则绑定
	 *
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	protected void dataBindComponentQuote(List<SiteComponent> listSiteComponent, List<Long> qsIds, long hostId, long siteId)
			throws JsonParseException, JsonMappingException, IOException {
		if (CollectionUtils.isEmpty(listSiteComponent)) {
			return;
		}
		if (!CollectionUtils.isEmpty(qsIds)) {
			List<SComponentQuoteSystem> findByHostSiteComponentIds = sComponentQuoteSystemServiceImpl.findByHostSiteComponentIds(hostId, siteId, qsIds);
			if (!CollectionUtils.isEmpty(findByHostSiteComponentIds)) {
				Iterator<SComponentQuoteSystem> iteratorSComponentQuoteSystem = findByHostSiteComponentIds.iterator();
				while (iteratorSComponentQuoteSystem.hasNext()) {
					SComponentQuoteSystem sComponentQuoteSystem = iteratorSComponentQuoteSystem.next();
					Iterator<SiteComponent> iteratorSiteComponent = listSiteComponent.iterator();
					while (iteratorSiteComponent.hasNext()) {
						SiteComponent siteComponent = iteratorSiteComponent.next();
						// 判断 组件数据id与组件引用系统数据中的组件id是否能够匹配，同时要求系统id数据必须不能为0
						if (siteComponent.getComponent().getId() != null && sComponentQuoteSystem.getComponentId() != null
								&& siteComponent.getComponent().getId().longValue() == sComponentQuoteSystem.getComponentId().longValue()
								&& sComponentQuoteSystem.getQuoteSystemId() != null && sComponentQuoteSystem.getQuoteSystemId().longValue() > 0L) {
							// 将 quoteSystem 写入到 siteComponent 数据中
							siteComponent.setQuoteSystem(sComponentQuoteSystem);
							// 获取系统数据
							SSystem sSystem = sSystemServiceImpl.findSSystemByIdHostSiteId(sComponentQuoteSystem.getQuoteSystemId(), hostId, siteId);
							if (sSystem == null) {
								break;
							}
							// 获取对应的数据
							if (siteComponent.getComponent().getTypeId() != null && siteComponent.getComponent().getTypeId().longValue() == 13L) {
								// 为文章列表组件
								dataBindComponentQuoteArticles(siteComponent, sComponentQuoteSystem, sSystem, hostId, siteId);
							} else if (siteComponent.getComponent().getTypeId() != null && siteComponent.getComponent().getTypeId().longValue() == 14L) {
								// 单个产品组件数据获取
								dataBindComponentQuoteProduct(siteComponent, sComponentQuoteSystem, sSystem);
							} else if (siteComponent.getComponent().getTypeId() != null && siteComponent.getComponent().getTypeId().longValue() == 15L) {
								// 产品列表组件
								dataBindComponentQuoteProducts(siteComponent, sComponentQuoteSystem, hostId, siteId);
							}
						}
					}
				}
			}

		}
	}

	protected void dataBindComponentQuoteArticles(SiteComponent siteComponent, SComponentQuoteSystem sComponentQuoteSystem, SSystem sSystem, long hostId,
			long siteId) throws JsonParseException, JsonMappingException, IOException {
		SPage sPage = sPageServiceImpl.findOne(sComponentQuoteSystem.getQuotePageId());
		Short type = sComponentQuoteSystem.getType();
		if (type != null && type.shortValue() == (short) 1) {
			// 通过 系统，分类，以及总数获取文章系统数据
			int limit = sComponentQuoteSystem.getTopCount();
			PageInfo<Article> pageInfoArticle = cArticleServiceImpl.findInfosBySystemCategoryIdReleasedAndPageLimit(hostId, siteId,
					sComponentQuoteSystem.getQuoteSystemId(), sComponentQuoteSystem.getQuoteSystemCategoryId(), "", 1, limit);
			List<Article> listArticle = pageInfoArticle != null ? pageInfoArticle.getList() : null;
			if (!CollectionUtils.isEmpty(listArticle)) {
				listArticle.forEach(item -> {
					if (sPage != null && sPage.getHostId().longValue() == sComponentQuoteSystem.getHostId().longValue()
							&& sPage.getSiteId().longValue() == sComponentQuoteSystem.getSiteId().longValue()) {

						SArticle sArticle = item.getSArticle();
						// 查询是否存在自定义链接如果存在则使用自定义链接
						SSystemItemCustomLink sSystemItemCustomLink = sSystemItemCustomLinkServiceImpl.findOkOneByHostSiteSystemItemId(hostId, siteId,
								sSystem.getId(), sArticle.getId());
						if (sSystemItemCustomLink == null) {
							item.setSiteHref(SiteUrlUtil.getPath(sPage, sArticle));
						} else {
							item.setSiteHref(SiteUrlUtil.getPath(sSystemItemCustomLink));
						}

						CategoryQuote categoryQuote = item.getCategoryQuote();
						if (categoryQuote != null && categoryQuote.getSCategories() != null) {
							item.setCateHref(SiteUrlUtil.getPath(sPage, categoryQuote.getSCategories()));
						}
					}
				});
				siteComponent.setArticles(listArticle);
			}
		} else if (type != null && type.shortValue() == (short) 2) {
			String quoteSystemItemIds = sComponentQuoteSystem.getQuoteSystemItemIds();
			if (!StringUtils.isEmpty(quoteSystemItemIds)) {
				@SuppressWarnings("unchecked")
				ArrayList<Long> ids = (ArrayList<Long>) objectMapper.readValue(quoteSystemItemIds, new TypeReference<ArrayList<Long>>() {
				});
				// 通过ids以及系统id获取文章系统数据
				List<Article> listArticle = cArticleServiceImpl.findInfosBySystemIdAndIds(
						new FeignFindInfosBySystemIdAndIds().setHostId(hostId).setSiteId(siteId).setSystemId(sSystem.getId()).setIds(ids));
				if (!CollectionUtils.isEmpty(listArticle)) {
					listArticle.forEach(item -> {
						if (sPage != null && sPage.getHostId().longValue() == sComponentQuoteSystem.getHostId().longValue()
								&& sPage.getSiteId().longValue() == sComponentQuoteSystem.getSiteId().longValue()) {

							SArticle sArticle = item.getSArticle();
							// 查询是否存在自定义链接如果存在则使用自定义链接
							SSystemItemCustomLink sSystemItemCustomLink = sSystemItemCustomLinkServiceImpl.findOkOneByHostSiteSystemItemId(hostId, siteId,
									sSystem.getId(), sArticle.getId());
							if (sSystemItemCustomLink == null) {
								item.setSiteHref(SiteUrlUtil.getPath(sPage, sArticle));
							} else {
								item.setSiteHref(SiteUrlUtil.getPath(sSystemItemCustomLink));
							}

							CategoryQuote categoryQuote = item.getCategoryQuote();
							if (categoryQuote != null && categoryQuote.getSCategories() != null) {
								item.setCateHref(SiteUrlUtil.getPath(sPage, categoryQuote.getSCategories()));
							}
						}
					});
					siteComponent.setArticles(listArticle);
				}
			}
		}

	}

	protected void dataBindComponentQuoteProduct(SiteComponent siteComponent, SComponentQuoteSystem sComponentQuoteSystem, SSystem sSystem)
			throws JsonParseException, JsonMappingException, IOException {
		String quoteSystemItemIds = sComponentQuoteSystem.getQuoteSystemItemIds();
		if (!StringUtils.isEmpty(quoteSystemItemIds)) {
			@SuppressWarnings("unchecked")
			ArrayList<Long> ids = (ArrayList<Long>) objectMapper.readValue(quoteSystemItemIds, new TypeReference<ArrayList<Long>>() {
			});
			if (!CollectionUtils.isEmpty(ids)) {
				Long productId = ids.get(0);
				if (productId != null && productId.longValue() > 0) {
					// 单个产品组件
					ProductDataTableForList findInfoBySystemProductId = cProductServiceImpl.findInfoBySystemProductId(sSystem.getHostId(), sSystem.getSiteId(),
							sSystem.getId(), productId);

					if (findInfoBySystemProductId != null && findInfoBySystemProductId.getSproduct() != null) {
						SPage sPage = sPageServiceImpl.findOne(sComponentQuoteSystem.getQuotePageId());
						if (sPage != null && sPage.getHostId().longValue() == sComponentQuoteSystem.getHostId().longValue()
								&& sPage.getSiteId().longValue() == sComponentQuoteSystem.getSiteId().longValue()) {
							// 查询是否存在自定义链接如果存在则使用自定义链接
							SSystemItemCustomLink sSystemItemCustomLink = sSystemItemCustomLinkServiceImpl.findOkOneByHostSiteSystemItemId(sSystem.getHostId(),
									sSystem.getSiteId(), sSystem.getId(), findInfoBySystemProductId.getSproduct().getId());
							if (sSystemItemCustomLink == null) {
								findInfoBySystemProductId.setSiteHref(SiteUrlUtil.getPath(sPage, findInfoBySystemProductId.getSproduct()));
							} else {
								findInfoBySystemProductId.setSiteHref(SiteUrlUtil.getPath(sSystemItemCustomLink));
							}
						}
					}

					siteComponent.setProductData(findInfoBySystemProductId);
				}
			}
		}
	}

	protected void dataBindComponentQuoteProducts(SiteComponent siteComponent, SComponentQuoteSystem sComponentQuoteSystem, long hostId, long siteId)
			throws JsonParseException, JsonMappingException, IOException {
		SPage sPage = sPageServiceImpl.findOne(sComponentQuoteSystem.getQuotePageId());
		Short type = sComponentQuoteSystem.getType();
		if (type != null && type.shortValue() == (short) 1) {
			PageInfo<ProductDataTableForList> data = cProductServiceImpl.findInfosByHostSiteSystemCategoryIdNameAndPageLimit(hostId, siteId,
					sComponentQuoteSystem.getQuoteSystemId(), sComponentQuoteSystem.getQuoteSystemCategoryId(), "", 1, sComponentQuoteSystem.getTopCount());
			if (data != null && data.getTotal() > 0 && !CollectionUtils.isEmpty(data.getList())) {
				List<ProductDataTableForList> list = data.getList();
				list.forEach(item -> {
					if (sPage != null && sPage.getHostId().longValue() == sComponentQuoteSystem.getHostId().longValue()
							&& sPage.getSiteId().longValue() == sComponentQuoteSystem.getSiteId().longValue()) {
						SProduct sproduct = item.getSproduct();
						// 查询是否存在自定义链接如果存在则使用自定义链接
						SSystemItemCustomLink sSystemItemCustomLink = sSystemItemCustomLinkServiceImpl.findOkOneByHostSiteSystemItemId(hostId, siteId,
								sproduct.getSystemId(), sproduct.getId());
						if (sSystemItemCustomLink == null) {
							item.setSiteHref(SiteUrlUtil.getPath(sPage, item.getSproduct()));
						} else {
							item.setSiteHref(SiteUrlUtil.getPath(sSystemItemCustomLink));
						}
					}
				});

				siteComponent.setProductsData(list);
			}
		} else if (type != null && type.shortValue() == (short) 2) {
			String quoteSystemItemIds = sComponentQuoteSystem.getQuoteSystemItemIds();
			if (!StringUtils.isEmpty(quoteSystemItemIds)) {
				@SuppressWarnings("unchecked")
				ArrayList<Long> ids = (ArrayList<Long>) objectMapper.readValue(quoteSystemItemIds, new TypeReference<ArrayList<Long>>() {
				});
				if (!CollectionUtils.isEmpty(ids)) {
					List<ProductDataTableForList> list = cProductServiceImpl.findInfosBySystemProductIds(hostId, siteId,
							sComponentQuoteSystem.getQuoteSystemId(), ids);
					if (CollUtil.isNotEmpty(list)) {
						list.forEach(item -> {
							if (sPage != null && sPage.getHostId().longValue() == sComponentQuoteSystem.getHostId().longValue()
									&& sPage.getSiteId().longValue() == sComponentQuoteSystem.getSiteId().longValue()) {

								SProduct sproduct = item.getSproduct();
								// 查询是否存在自定义链接如果存在则使用自定义链接
								SSystemItemCustomLink sSystemItemCustomLink = sSystemItemCustomLinkServiceImpl.findOkOneByHostSiteSystemItemId(hostId, siteId,
										sproduct.getSystemId(), sproduct.getId());
								if (sSystemItemCustomLink == null) {
									item.setSiteHref(SiteUrlUtil.getPath(sPage, item.getSproduct()));
								} else {
									item.setSiteHref(SiteUrlUtil.getPath(sSystemItemCustomLink));
								}
							}
						});
					}
					siteComponent.setProductsData(list);
				}
			}
		}
	}

	@Override
	public List<SiteComponent> findInfosByHostSitePageParentIdAndAreaStatus(long hostId, long siteId, long pageId, long parentId, short area, short status)
			throws JsonParseException, JsonMappingException, IOException {
		List<SComponent> listSComponent = sComponentServiceImpl.findInfosByHostSitePageParentIdAndAreaStatus(hostId, siteId, pageId, parentId, area, status);

		List<SiteComponent> listSiteComponent = new ArrayList<SiteComponent>();

		// 需要一次性查询资源数据库的ids
		List<Long> aimIds = new ArrayList<>();
		// 需要一次性查询引用系统数据的ids
		List<Long> qsIds = new ArrayList<>();
		Iterator<SComponent> iterator = listSComponent.iterator();
		while (iterator.hasNext()) {
			SComponent sComponent = iterator.next();

			// 是否需要查询资源库
			if (mustSelectRepertoryTypeId(sComponent.getTypeId())) {
				aimIds.add(sComponent.getId());
			}

			if (mustSelectQuoteSystemConfig(sComponent.getTypeId())) {
				qsIds.add(sComponent.getId());
			}

			SiteComponent siteComponent = new SiteComponent();
			siteComponent.setComponent(sComponent);
			listSiteComponent.add(siteComponent);
		}

		// 给组件数据补充资源库数据引用部分
		dataBindRepertoryQuote(listSiteComponent, aimIds, hostId, siteId);

		// 给组件数据补充系统资源引用部分数据
		dataBindComponentQuote(listSiteComponent, qsIds, hostId, siteId);

		return listSiteComponent;
	}

	@Override
	public SiteComponentSimple findComponentSimpleByHostSiteTypeIdStatusNotAndCreate(long hostId, long siteId, long typeId, short status)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		SComponentSimple sComponentSimple = sComponentSimpleServiceImpl.findByHostSiteTypeIdStatus(hostId, siteId, typeId, status);
		if (sComponentSimple == null && status == (short) -1) {
			sComponentSimple = sComponentSimpleServiceImpl.findByHostSiteTypeIdNotAndCreate(hostId, siteId, typeId);
		}
		if (sComponentSimple == null) {
			return null;
		}
		List<RepertoryQuote> listRepertoryQuote = sRepertoryQuoteServiceImpl.findRepertoryQuoteByHostSiteTypeAimId(hostId, siteId, (short) 12,
				sComponentSimple.getId(), "`s_repertory_quote`.`order_num` ASC");

		SysComponentType sysComponentType = sysComponentTypeServiceImpl.findOne(sComponentSimple.getTypeId());

		SiteComponentSimple siteComponentSimple = new SiteComponentSimple();
		siteComponentSimple.setComponentSimple(sComponentSimple).setRepertoryQuote(listRepertoryQuote).setComponentType(sysComponentType);
		return siteComponentSimple;
	}

	@Override
	@Transactional
	public SiteComponentSimple updateComponentSimple(SiteComponentSimple siteComponentSimple)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		SComponentSimple componentSimple = siteComponentSimple.getComponentSimple();
		Long hostId = componentSimple.getHostId();
		Long siteId = componentSimple.getSiteId();
		SComponentSimple updateById = sComponentSimpleServiceImpl.updateById(componentSimple);
		if (updateById == null) {
			throw new RuntimeException("更新简易组件失败！ SComponentSimple： " + componentSimple.toString());
		}
		List<RepertoryQuote> repertoryQuote = siteComponentSimple.getRepertoryQuote();
		if (CollectionUtils.isEmpty(repertoryQuote)) {
			boolean bool = sRepertoryQuoteServiceImpl.deleteByHostSiteAimIdAndType(hostId, siteId, (short) 12, componentSimple.getId());
			if (!bool) {
				throw new RuntimeException("清空资源引用失败！");
			}
		} else {
			List<SRepertoryQuote> listSRepertoryQuote = sRepertoryQuoteServiceImpl.findByHostSiteAimIdAndType(hostId, siteId, (short) 12,
					componentSimple.getId());
			if (CollectionUtils.isEmpty(listSRepertoryQuote)) {
				// 逐个添加
				int orderNum = 1;
				for (RepertoryQuote rQuote : repertoryQuote) {
					HRepertory hRepertory = rQuote.getHRepertory();
					if (hRepertory == null) {
						throw new RuntimeException("存在为空的仓库资源！");
					}
					SRepertoryQuote srQuote = new SRepertoryQuote();
					srQuote.setHostId(hostId).setSiteId(siteId).setRepertoryId(hRepertory.getId()).setType((short) 12).setAimId(componentSimple.getId())
							.setOrderNum(orderNum++).setConfig("");
					SRepertoryQuote insert = sRepertoryQuoteServiceImpl.insert(srQuote);
					if (insert == null) {
						throw new RuntimeException("插入资源失败！ SRepertoryQuote: " + srQuote.toString());
					}
				}
			} else {
				// 不全部为空的情况下
				if (listSRepertoryQuote.size() == repertoryQuote.size()) {
					// 全部更新
					int orderNum = 1;
					for (int i = 0; i < listSRepertoryQuote.size(); i++) {
						SRepertoryQuote sRepertoryQuote = listSRepertoryQuote.get(i);
						RepertoryQuote rQuote = repertoryQuote.get(i);
						HRepertory hRepertory = rQuote.getHRepertory();
						if (hRepertory == null) {
							throw new RuntimeException("存在为空的仓库资源！");
						}
						sRepertoryQuote.setRepertoryId(hRepertory.getId()).setOrderNum(orderNum++);
						SRepertoryQuote update = sRepertoryQuoteServiceImpl.updateById(sRepertoryQuote);
						if (update == null) {
							throw new RuntimeException("更新资源失败！sRepertoryQuote: " + sRepertoryQuote.toString());
						}
					}
				} else if (listSRepertoryQuote.size() > repertoryQuote.size()) {
					// 更新后删除多余
					int orderNum = 1;
					for (int i = 0; i < listSRepertoryQuote.size(); i++) {
						SRepertoryQuote sRepertoryQuote = listSRepertoryQuote.get(i);
						if (i < repertoryQuote.size()) {
							RepertoryQuote rQuote = repertoryQuote.get(i);
							HRepertory hRepertory = rQuote.getHRepertory();
							if (hRepertory == null) {
								throw new RuntimeException("存在为空的仓库资源！");
							}
							sRepertoryQuote.setRepertoryId(hRepertory.getId()).setOrderNum(orderNum++);
							SRepertoryQuote update = sRepertoryQuoteServiceImpl.updateById(sRepertoryQuote);
							if (update == null) {
								throw new RuntimeException("更新资源失败！sRepertoryQuote: " + sRepertoryQuote.toString());
							}
						} else {
							sRepertoryQuoteServiceImpl.deleteById(sRepertoryQuote.getId());
						}
					}
				} else if (listSRepertoryQuote.size() < repertoryQuote.size()) {
					// 更新后新增不足
					int orderNum = 1;
					for (int i = 0; i < repertoryQuote.size(); i++) {
						RepertoryQuote rQuote = repertoryQuote.get(i);
						HRepertory hRepertory = rQuote.getHRepertory();
						if (hRepertory == null) {
							throw new RuntimeException("存在为空的仓库资源！");
						}
						if (i < listSRepertoryQuote.size()) {
							SRepertoryQuote sRepertoryQuote = listSRepertoryQuote.get(i);
							sRepertoryQuote.setRepertoryId(hRepertory.getId()).setOrderNum(orderNum++);
							SRepertoryQuote update = sRepertoryQuoteServiceImpl.updateById(sRepertoryQuote);
							if (update == null) {
								throw new RuntimeException("更新资源失败！sRepertoryQuote: " + sRepertoryQuote.toString());
							}
						} else {
							SRepertoryQuote srQuote = new SRepertoryQuote();
							srQuote.setHostId(hostId).setSiteId(siteId).setRepertoryId(hRepertory.getId()).setType((short) 12).setAimId(componentSimple.getId())
									.setOrderNum(orderNum++).setConfig("");
							SRepertoryQuote insert = sRepertoryQuoteServiceImpl.insert(srQuote);
							if (insert == null) {
								throw new RuntimeException("插入资源失败！ SRepertoryQuote: " + srQuote.toString());
							}
						}
					}
				}
			}
		}

		return findComponentSimpleByHostSiteTypeIdStatusNotAndCreate(hostId, siteId, componentSimple.getTypeId(), (short) -1);
	}

	@Override
	public List<SiteComponentSimple> findComponentSimpleInfosByHostSiteIdStatus(long hostId, long siteId, short status, String orderBy)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		List<SComponentSimple> listSComponentSimple = sComponentSimpleServiceImpl.findInfosByHostSiteIdStatus(hostId, siteId, status, orderBy);
		if (CollectionUtils.isEmpty(listSComponentSimple)) {
			return null;
		}
		List<SiteComponentSimple> result = new ArrayList<>();
		Iterator<SComponentSimple> iterator = listSComponentSimple.iterator();
		while (iterator.hasNext()) {
			SiteComponentSimple siteComponentSimple = new SiteComponentSimple();
			SComponentSimple sComponentSimple = iterator.next();
			SysComponentType sysComponentType = sysComponentTypeServiceImpl.findOne(sComponentSimple.getTypeId());
			List<RepertoryQuote> listRepertoryQuote = sRepertoryQuoteServiceImpl.findRepertoryQuoteByHostSiteTypeAimId(hostId, siteId, (short) 12,
					sComponentSimple.getId(), "`s_repertory_quote`.`order_num` ASC");

			siteComponentSimple.setComponentSimple(sComponentSimple).setComponentType(sysComponentType).setRepertoryQuote(listRepertoryQuote);
			result.add(siteComponentSimple);
		}
		return result;
	}

	@Override
	public List<FormComponent> findFormInfosByHostSiteIdStatusOrder(long hostId, long siteId, short status, String orderBy) {
		List<SComponentForm> listSComponentForm = sComponentFormServiceImpl.findInfosByHostSiteIdStatus(hostId, siteId, status, orderBy);
		if (CollectionUtils.isEmpty(listSComponentForm)) {
			return null;
		}

		return makeFormComponent(listSComponentForm);
	}

	@Override
	public List<FormComponent> findFormInfosByHostSiteFormIdStatusOrder(long hostId, long siteId, long formId, short status, String orderBy) {
		List<SComponentForm> listSComponentForm = sComponentFormServiceImpl.findInfosByHostSiteFormIdStatus(hostId, siteId, formId, status, orderBy);
		if (CollectionUtils.isEmpty(listSComponentForm)) {
			return null;
		}

		return makeFormComponent(listSComponentForm);
	}

	/**
	 * 通过 参数 List<FormComponent> 制作生成结果 List<FormComponent> 数据
	 *
	 * @param listSComponentForm
	 * @return
	 */
	protected List<FormComponent> makeFormComponent(List<SComponentForm> listSComponentForm) {
		List<FormComponent> result = new ArrayList<>();
		Iterator<SComponentForm> iterator = listSComponentForm.iterator();
		while (iterator.hasNext()) {
			SComponentForm sComponentForm = iterator.next();

			FormComponent formComponent = new FormComponent();
			formComponent.setComponentForm(sComponentForm);

			result.add(formComponent);
		}

		return result;
	}

	@Transactional
	@Override
	public void delete(long hostId, long siteId, long pageId) {
		// 删除系统组件引用的数据表
		sComponentQuoteSystemServiceImpl.deleteByHostSitePageId(hostId, siteId, pageId);
		// 删除引用的资源数据表
		sRepertoryQuoteServiceImpl.deleteSComponentRepertoryByHostSitePageId(hostId, siteId, pageId);
		// 删除
		sComponentServiceImpl.deleteByHostSitePageId(hostId, siteId, pageId);
	}
}
